﻿# -*- coding:utf-8 -*-
#
# склад
from django.shortcuts import render_to_response
from django.template import RequestContext, Context
from django.contrib.auth.decorators import login_required
from django.contrib.auth.decorators import permission_required
from django.contrib import messages
from sklad.models import Category, Part
from sklad.contextprocessors import category_proc
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse


@login_required
@permission_required('sklad.view_part')
def index(request): 
    request.session["current_category"] = None
    context = Context({
    })
    return render_to_response('sklad/index.html', context, context_instance=RequestContext(request, processors=[category_proc]))


@login_required
@permission_required('sklad.view_part')
def search(request): 
    try:
        query = request.GET.get('search_query', '')
    except ValueError:
        query = ''
    
    if query == '':
        #request.user.message_set.create(message=u"<font color='red'>Пустой запрос.</font>")
        messages.warning(request, 'Пустой запрос.')
        try:
            referer = request.META.get('HTTP_REFERER', '')
            return HttpResponseRedirect(referer) 
        except ValueError:
            return HttpResponseRedirect(reverse('index')) 
      
    search_result = Part.objects.filter(name__icontains=query)   #.filter(code__icontains=query)
    
    context = Context({
        'query': query,
        'search_result': search_result,
    })
    return render_to_response('sklad/search.html', context, context_instance=RequestContext(request, processors=[category_proc]))
    
    